<?php

namespace App\Repository;

use App\Entity\MoneyLogType;
use App\Entity\MoneyStatic;
use App\Entity\MoneyType;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Repository\DocumentRepository;

/**
 * @method MoneyStatic|null find($id, $lockMode = null, $lockVersion = null)
 * @method MoneyStatic|null findOneBy(array $criteria, array $orderBy = null)
 * @method MoneyStatic[]    findAll()
 * @method MoneyStatic[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class MoneyStaticRepository extends DocumentRepository
{
    public function __construct(DocumentManager $dm)
    {
        parent::__construct($dm, $dm->getUnitOfWork(),$dm->getClassMetadata(MoneyStatic::class));
    }

    public function getUserMoneyStaticByType(User $user, MoneyType $moneyType,MoneyLogType $logType)
    {
        $static = $this->findOneBy(array(
            "user"=>$user,
            "moneyType"=>$moneyType,
            "logType"=>$logType
        ));
        if (!$static) {
            $static = new MoneyStatic();
            $static->setMoney(0)
                ->setUser($user)
                ->setMoneyType($moneyType)
                ->setLogType($logType);
            $this->dm->persist($logType);
            $this->dm->flush();
        }
        return $static;
    }
}
